package com.ezregex;

import java.util.Arrays;
import java.util.List;

public class RegexBuilder {

    List<RegexSegment> regexSegments;

    private RegexBuilder(RegexSegment... segments) {
        regexSegments = Arrays.asList(segments);
    }

    public static String aRegexWith(RegexSegment... segments) {
        return new RegexBuilder(segments).build();
    }

    public String build() {
        String regex = "";
        for (RegexSegment regexSegment : regexSegments) {
            switch (regexSegment.getCardinalityType()) {
                case EXACTLY_ONCE:
                    if (regexSegment.getSegmentType() == SegmentType.SEQUENCE) {
                        regex += "[" + regexSegment.getRegexSegment() + "]";
                    } else {
                        regex += regexSegment.getRegexSegment();
                    }
                    break;
                case NUMBER_OF_TIMES:
                    if (regexSegment.getSegmentType() == SegmentType.SEQUENCE) {
                        regex += "[" + regexSegment.getRegexSegment() + "]" + "{" + regexSegment.getCardinality() + "}"; // TODO: implement the look behind here
                    } else {
                        regex += "(" + regexSegment.getRegexSegment() + ")" + "{" + regexSegment.getCardinality() + "}";
                    }
                    break;
                case AT_LEAST_ONCE:
                    if (regexSegment.getSegmentType() == SegmentType.SEQUENCE) {
                        regex += "[" + regexSegment.getRegexSegment() + "]" + "+"; // TODO: implement the look behind here
                    } else {
                        regex += "(" + regexSegment.getRegexSegment() + ")" + "+";
                    }
                    break;
                case INTERVAL:
                    if (regexSegment.getSegmentType() == SegmentType.SEQUENCE) {
                        regex += "[" + regexSegment.getRegexSegment() + "]" + "{" + regexSegment.getCardinalityFromValue() + "," + regexSegment.getCardinalityToValue() + "}"; // TODO: implement the look behind here
                    } else {
                        regex += "(" + regexSegment.getRegexSegment() + ")" + "{" + regexSegment.getCardinalityFromValue() + "," + regexSegment.getCardinalityToValue() + "}";
                    }
                    break;
                default:
                    regex += regexSegment.getRegexSegment();
                    break;
            }
        }
        return regex;
    }

    public static interface BuildStep {

        public String build();

    }


}
